<template>
  <div class="context-menu">
    <slot></slot>
    <Teleport to="body">
      <transition name="fade-scale">
        <div
          class="content-menu"
          :style="{
            top: `${top}px`,
            left: `${left}px`,
            width: `${width}px`,
          }"
          v-if="show"
        >
          <div class="menu-list">
            <div
              class="menu-item"
              v-for="(item, index) in menuContext"
              :key="index"
              @click.stop="handel(item)"
            >
              {{ item.label }}
            </div>
          </div>
        </div>
      </transition>
    </Teleport>
  </div>
</template>

<script>
import Teleport from "@/components/Teleport";

export default {
  name: "context-menu",
  components: {
    Teleport,
  },
  props: {
    menuContext: {
      type: Array,
      default: () => {
        return [];
      },
    },
    width: {
      type: Number,
      default: 98,
    },
    height: {
      type: Number,
      default: 180,
    },
  },
  data() {
    return {
      show: false,
      top: 0,
      left: 0,
    };
  },
  mounted() {
    this.$el.addEventListener("contextmenu", this.openMenu);
    window.addEventListener("click", this.closeMenu, true);
    this.$el.addEventListener("contextmenu", this.openMenu, true);
  },
  // 销毁事件
  beforeDestroy() {
    this.$el.removeEventListener("contextmenu", this.openMenu);
    window.removeEventListener("click", this.closeMenu);
  },
  methods: {
    openMenu(e) {
      e.preventDefault();
      e.stopPropagation();
      this.show = true;
      this.left = e.clientX;
      this.top = e.clientY;
    },
    closeMenu(e) {
      if (e.srcElement._prevClass === "menu-item") {
        return false;
      }
      this.show = false;
    },
    handel(data) {
      console.log(data, "======");
      this.show = false;
      this.$emit("onSelected", data);
    },
  },
};
</script>

<style lang="scss" scoped>
.content-menu {
  position: fixed;
  border-radius: 4px;
  padding: 4px;
  background: var(--body-background);
  border: 1px solid var(--main-border);
  box-shadow: 0 2px 12px 0 var(--main-shadow);
  overflow: hidden;
  z-index: 1024;
}

.menu-list {
  width: 100%;
  font-size: 12px;

  .menu-item {
    width: 100%;
    height: 24px;
    line-height: 24px;
    text-align: center;
    color: var(--main-color);
    border-bottom: 1px solid var(--main-border);

    &:hover {
      cursor: pointer;
      color: var(--main-hover);
      background: var(--main-shadow);
      border-radius: 2px;
    }
  }

  .menu-item:last-child {
    border-bottom: none;
  }
}
</style>